#!/bin/bash

############## COMMAND EXAMPLES ################
## ENCRYPT AES-256 SALTED by OPENSSL
## openssl aes-256-ctr -a -salt -pbkdf2 -in plain.openssl -out encrypted.openssl -pass pass:'hello'

## ENCRYPT AES-256 by GPG
## gpg --cipher-algo AES256 --symmetric --batch --yes --passphrase 1234 --output encrypted.file plain.file

## ENCRYPT XORON EBS
## $HOME/xoronos/build/xrnlib-cli ebs -o $HOME/xoronos/cache/filecompressed_symblock.rnd -i attack-plan.txt -m $HOME/xoronos/cache/matrix.decompressed -k $HOME/xoronos/cache/pri.json -b 0 1

## DECRYPT AES-256 SALTED
## openssl aes-256-ctr -d -a -pbkdf2 -in encrypted.openssl -out decrypted.openssl -pass pass:'hello' 

## DECRYPT AES-256 by GPG
## gpg -d --batch --yes --passphrase 1234 --output decrypted.gpg encrypted.gpg

############################################################
# Help                                                     #
############################################################
Help()
{
   # Display Help
   echo
   echo "$(basename "$0") [-h] [-i <command1,command2,...>] [-n <occurr>] [-o <filename.json>]"
   echo "perfromance evaluates the timing performance of a number of occurrences of a specified command."
   echo
   echo "Syntax: ./perfromance.sh [-h|i|n|o]"
   echo
   echo "Options:"
   echo "h     Print this Help."
   echo "i     Input commands."
   echo "n     Set the test occurrences."
   echo "o     Print to a JSON file."
   echo
   echo "Usage Example:"
   echo "./perfromance.sh -i \"gpg --cipher-algo AES256 --symmetric --batch --yes --passphrase 1234 --output encrypted.gpg plain.gpg,openssl aes-256-ctr -a -salt -pbkdf2 -in plain.openssl -out encrypted.openssl -pass pass:'hello',openssl aes-256-ctr -d -a -pbkdf2 -in encrypted.openssl -out decrypted.openssl -pass pass:'hello',gpg -d --batch --yes --passphrase 1234 --output decrypted.gpg encrypted.gpg\" -n 3"
   echo
}

############################################################
# Banner                                                     #
############################################################
#cat banner.txt | gzip | base64
base64 -d <<<"H4sIAAAAAAAAA51Uy26EMAy89yt8W5Dq+N5KVfcLetuTtd6v6IWQb68nLI8gsgUSSBwFjyeOGaJ9
zayy8bYTQMjiMQQbgpqPMCPFgxwiXYwUkX28AOEoB8RsCX4mmCJV/F8gBPiqnyIieKwxeMWh5rEX
oR5zJ8J2C5xS4nAaQUajP4kgE49jHHQ0prz0qy/WCM9KnFamAUfnNCAE4rQqzhWCl0Bwuio6ftfR
D+I/QD/n8JPIIecfbYFg1t3d0Xpstk5X7jhDYk7C0RQsPvJb5GJG8NAe2b2CY2AhY/ZkSIMmYu+r
RM4IjT/Oovlue6/lPoiYmF29tjF4bfuEIsdimq4FB9+WThpr1TzdrSqpMvMvo914NBfrbBeZbCjz
aL0LMEi/6P9W3AVoTIbfh2y6vEIYfN+ZL3tcNxGytkHZFhYNQrdQvVJ0CwRom2Vlyyr3oKfSPRaq
N+zXEdCbrG9zb6y0aczWFgL2cekSszrnF5mx2c5FEWsI59ofP8Bv/LQGAAA=" | gunzip
echo
############################################################
############################################################
# Main program                                             #
############################################################
############################################################

# Set variables
occurr=1

############################################################
# Process the input options. Add options as needed.        #
############################################################
# Get the options
while getopts ":hi:n:o:" option; do #When using getopts, putting : after an option character means that it requires an argument (i.e., 'h').
   case "${option}" in
      h) # display Help
         Help >&2
         exit 2
         ;;
      i) # Enter a command
         cmd=$OPTARG
         ;;
      o) # Enter an output filename
         out=$OPTARG
         if [ -f ${out} ]; then
            echo "${out} already exist! Do you want to overwrite it?"
            select yn in "Yes" "No"; do
               case $yn in
                  Yes ) rm -rf ${out}; break;;
                  No ) break;;
               esac
            done
         fi
         ;;
      n) # Execute the test <occurr> times
         occurr=$OPTARG
         ;;
      : )
        echo "Missing option argument for -$OPTARG" >&2; exit 1;;
      *  )
        echo "Unimplemented option: -$OPTARG" >&2; exit 1;;
     \?) # Invalid option
         echo "Error: Invalid option" >&2
         ;;
   esac
done
echo
# mandatory arguments
if [ ! "$cmd" ]; then
  Help >&2
  echo "perfromance: error: missing a mandatory option (-i). Use -h for help"
  exit 1
fi

readarray -td, cmd_array < <(printf '%s' "${cmd}"); declare -p cmd_array >/dev/null ## < < to remove the final newline on the last item of the array added by <<<

for index in "${cmd_array[@]}"
do
runtime_bc=0
echo "Executing \"${index}\" command..."
   for i in $(seq 1 $occurr)
   do
      start=`date +%s.%N` #This command computes the number of seconds.nanoseconds since 01/01/1970 to the current time
      ${index} #> /dev/null
      end=`date +%s.%N`
      runtime_bc=$( echo "$runtime_bc + $( echo \"$end - $start\" | bc -l)" | bc -l )
   done
   
   result=$(echo "{\"command\": \"${index}\", \"execution_time\": \"${runtime_bc}\", \"test_occurrences\": \"${occurr}\", \"average_time\": \"$( echo "scale=9; ${runtime_bc} / ${occurr}" | bc -l )\"}")

   if [ ! "$out" ]; then
      echo
      echo ${result} | python -c "import json, sys, collections; print(json.dumps(json.loads(sys.stdin.read(), object_pairs_hook=collections.OrderedDict), indent=4))"
      echo
   else
      echo ${result} | python -c "import json, sys, collections; print(json.dumps(json.loads(sys.stdin.read(), object_pairs_hook=collections.OrderedDict), indent=4))" >> $out
      echo "Result correctly stored in ${out} file"
      echo
   fi
done
